package com.nhaycungbibi.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tubeilike.entity.Tube;
import com.tubeilike.entity.TubesFeed;
import com.tubeilike.service.TubeService;

public class TubeSearchController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		String uri = URLDecoder.decode(request.getRequestURI(), "UTF-8");
		// search by url
		if (uri.contains("http://www.youtube.com/watch?v")) {
			Pattern compiledPattern = Pattern.compile(
					"(?:videos\\/|v=)([\\w-]+)", Pattern.CASE_INSENSITIVE);
			Matcher matcher = compiledPattern.matcher(uri);
			if (matcher.find()) {
				String id = matcher.group();
				id = id.substring(2, id.length());
				System.out.println(id);
				Tube tub = TubeService.searchById(id, true);
				// request.setAttribute("detail", tub);
				// request.setAttribute("categories", CategoryModel.all());
				// request.setAttribute("url", request.getRequestURL());
				// request.getRequestDispatcher("/tube_detail.jsp").forward(
				// request, response);
				List<Tube> list = new ArrayList<Tube>();
				list.add(tub);
				TubesFeed result = new TubesFeed();
				result.setCurrentPage(1);
				result.setTotalResult(1);
				result.setListTube(list);
				request.setAttribute("url", request.getRequestURL());
				request.setAttribute("result", result);
				request.setAttribute("key", tub.getTitle().getValue());
				request.getRequestDispatcher("/tube_show.jsp").forward(request,
						response);
			} else {

			}

		} else {
			// search by input key.
			String[] splitted = request.getRequestURI().split("/");
			String key = null;
			int currentPage = 1;
			if (splitted.length == 3) {
				key = URLDecoder.decode(splitted[2], "UTF-8");
			} else if (splitted.length == 4) {
				key = URLDecoder.decode(splitted[2], "UTF-8");
				try {
					currentPage = Integer.parseInt(splitted[3]);
				} catch (Exception e) {
					currentPage = 1;
				}
			} else {
				response.sendRedirect("/home");
			}
			try {
				System.out.println("Keyword to search : " + key);
				TubesFeed result = TubeService.searchByKey(key, currentPage, 1);
				request.setAttribute("url", request.getRequestURL());
				request.setAttribute("result", result);
				request.setAttribute("key", key);
				request.getRequestDispatcher("/tube_show.jsp").forward(request,
						response);
			} catch (Exception e) {
				response.sendRedirect("/home");
			}
		}
	}
}
